package com.mediacloud.app.newsmodule.fragment.baoliao.holder;

import android.content.Intent;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mediacloud.app.assembly.views.CornerBlurView;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.nav2.utils.DateUtils;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.activity.microlive.BaseRecyclerAdapter;
import com.mediacloud.app.newsmodule.activity.microlive.XdNineGridDivider;
import com.mediacloud.app.newsmodule.fragment.activity.VideoPreActivity;
import com.mediacloud.app.newsmodule.fragment.baoliao.adapter.BaoLiaoListGridAdapter;
import com.mediacloud.app.newsmodule.fragment.baoliao.adapter.BaoLiaoNavListAdapter;
import com.mediacloud.app.newsmodule.model.baoliao.list.list.BaoNiaoListItem;
import com.mediacloud.app.newsmodule.model.baoliao.list.list.BaoNiaoMedia;
import com.mediacloud.app.model.news.BaoLiaoMeta;
import com.mediacloud.app.newsmodule.utils.GridLayoutSpanCountUtils;
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils;
import com.mediacloud.app.model.utils.ViewUtils;
import com.tencent.qcloud.tim.uikit.utils.DateTimeUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class BaoLiaoNavListImgVideoHolder extends BaoLiaoNavListPureTxtHolder implements BaoLiaoNavListAdapter.IBaoLiaoListHolder, BaseRecyclerAdapter.ItemClickListener {
    RecyclerView baoniaogrid;
    BaoLiaoListGridAdapter baoliaogridAdapter;
    GridLayoutManager gridLayoutManager;
    RelativeLayout containerLayout;
    CornerBlurView posterImg;
    ImageView playTagImg;
    TextView videoTime;

    private int lastHeight = -1;

    private boolean hasSetSpanCount = false;


    private String TAG = BaoLiaoNavListImgVideoHolder.class.getSimpleName();

    public BaoLiaoNavListImgVideoHolder(View view, int viewType) {
        this(view);
        hasSetSpanCount = true;
        int model = GridLayoutSpanCountUtils.ItemTypeSpec.getMode(viewType);
        int spanCount = GridLayoutSpanCountUtils.calculateSpanCount(model >> GridLayoutSpanCountUtils.ItemTypeSpec.MODE_SHIFT);
        gridLayoutManager.setSpanCount(spanCount);
        Log.w(TAG, "BaoLiaoNavListImgVideoHolder spanCount " + spanCount + " model " + (model >> GridLayoutSpanCountUtils.ItemTypeSpec.MODE_SHIFT));
        baoliaogridAdapter = new BaoLiaoListGridAdapter(itemView.getContext(), spanCount);
        baoniaogrid.setAdapter(baoliaogridAdapter);
        baoliaogridAdapter.itemClickListener = this;
        baoliaogridAdapter.getData().clear();
        for (int i = 0; i < model >> GridLayoutSpanCountUtils.ItemTypeSpec.MODE_SHIFT; i++) {
            baoliaogridAdapter.getData().add(new BaoNiaoMedia());
        }
        baoliaogridAdapter.notifyDataSetChanged();
    }

    public BaoLiaoNavListImgVideoHolder(View view) {
        super(view);
        containerLayout = view.findViewById(R.id.imageLayout);
        posterImg = view.findViewById(R.id.image);
        playTagImg = view.findViewById(R.id.playTag);
        videoTime = view.findViewById(R.id.tv_videotime);
        baoniaogrid = view.findViewById(R.id.baoniaogrid);
        gridLayoutManager = ViewUtils.generateRecyclerGridLayoutManager(view.getContext(), true, 3);
        baoniaogrid.setLayoutManager(gridLayoutManager);
        baoniaogrid.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (itemView != null && itemView.getParent() != null && itemView.getParent() instanceof RecyclerView && event.getAction() == MotionEvent.ACTION_UP)
                    itemView.performClick();
                return false;
            }
        });

        baoniaogrid.addItemDecoration(new XdNineGridDivider(itemView.getContext().getResources().getDimensionPixelSize(R.dimen.dimen2)));

    }

    @Override
    public void updateData(BaoNiaoListItem item, int position) {
        super.updateData(item, position);
        itemView.setTag(R.id.tagSaveId, item);
        if (item.baoNiaoMediaList == null) {
            item.baoNiaoMediaList = BaoNiaoMedia.parseBaoLiaoMediaListNew(item, position);
        }
        if (baoliaogridAdapter == null) {
            baoliaogridAdapter = new BaoLiaoListGridAdapter(itemView.getContext());
            baoniaogrid.setAdapter(baoliaogridAdapter);
            baoliaogridAdapter.itemClickListener = this;
        }
        //  if (!hasSetSpanCount) {//刷新会闪烁，屏蔽
        gridLayoutManager.setSpanCount(GridLayoutSpanCountUtils.calculateSpanCount(item.baoNiaoMediaList.size()));
        baoliaogridAdapter.setSpancount(gridLayoutManager.getSpanCount());
        // }
        baoliaogridAdapter.getData().clear();
        baoliaogridAdapter.getData().addAll(item.baoNiaoMediaList);
        baoliaogridAdapter.notifyDataSetChanged();
        if (item.baoNiaoMediaList != null && item.baoNiaoMediaList.size() == 1 && item.baoNiaoMediaList.get(0).isVideo) {
            //当切只有一个视频的时候，就不用recycler显示了
            baoniaogrid.setVisibility(View.GONE);
            containerLayout.setVisibility(View.VISIBLE);
            setVideo(item.baoNiaoMediaList.get(0));
        } else {
            baoniaogrid.setVisibility(View.VISIBLE);
            containerLayout.setVisibility(View.GONE);
        }
    }

    //当只有一个视频的时候的设置
    private void setVideo(BaoNiaoMedia baoNiaoMedia) {
        JSONArray formats = baoNiaoMedia.videoObj.optJSONArray("formats");
        if (formats != null && formats.length() > 0) {
            try {
                posterImg.load(((JSONObject) formats.get(0)).optString("image"), true);
                if(!TextUtils.isEmpty(((JSONObject) formats.get(0)).optString("duration"))){
                    videoTime.setText(DateUtils.millsecondToMinuteSecond(Integer.parseInt((((JSONObject) formats.get(0)).optString("duration"))) * 1000));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        posterImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (videoListPlayerUtil == null) {
                    itemView.performClick();
                    return;
                }
                videoListPlayerUtil.setPlayerContainer(itemView, containerLayout, posterImg);
                JSONArray formats = baoNiaoMedia.videoObj.optJSONArray("formats");
                if (formats != null && formats.length() > 0) {
                    try {
                        videoListPlayerUtil.setVideoData(((JSONObject) formats.get(0)).optString("image"), ((JSONObject) formats.get(0)).optString("url"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        posterImg.setOnClickListener(v -> {
            if (videoListPlayerUtil == null) {
                itemView.performClick();
                return;
            }
            videoListPlayerUtil.setPlayerContainer(itemView, containerLayout, posterImg);
            JSONArray formatsData = baoNiaoMedia.videoObj.optJSONArray("formats");
            if (formatsData != null && formatsData.length() > 0) {
                try {
                    videoListPlayerUtil.setVideoData(((JSONObject) formatsData.get(0)).optString("image"), ((JSONObject) formatsData.get(0)).optString("url"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onItemClick(int index, boolean isFromAdaptor, BaseRecyclerAdapter adapter) {
        BaoNiaoListItem baoNiaoListItem = itemView.getTag(R.id.tagSaveId) != null ? (BaoNiaoListItem) itemView.getTag(R.id.tagSaveId) : null;

        if (baoNiaoListItem == null) {
            return;
        }

        BaoNiaoMedia baoNiaoMedia = baoliaogridAdapter.getItem(index);
        if (baoNiaoMedia.isVideo) {
            BaoLiaoMeta meta = new BaoLiaoMeta();
            meta.setId(baoNiaoListItem.getId());
            meta.setAvatar(baoNiaoListItem.getAvatar());
            meta.setNickName(baoNiaoListItem.getNickName());
            meta.setFavorCount((int) baoNiaoListItem.getFavorCount());
            List<String> videoUrl = new ArrayList<>();
            if (baoNiaoListItem.getTipoffinfoList() != null && baoNiaoListItem.getTipoffinfoList().size() > 0) {
                if (baoNiaoListItem.getTipoffinfoList().get(0).getLiveAddress() != null && baoNiaoListItem.getTipoffinfoList().get(0).getLiveAddress().size() > 0) {
                    if (baoNiaoListItem.getTipoffinfoList().get(0).getLiveAddress().get(0).getFormats() != null && baoNiaoListItem.getTipoffinfoList().get(0).getLiveAddress().get(0).getFormats().size() > 0) {
                        for (int i = 0; i < baoNiaoListItem.getTipoffinfoList().get(0).getLiveAddress().get(0).getFormats().size(); i++) {
                            videoUrl.add(baoNiaoListItem.getTipoffinfoList().get(0).getLiveAddress().get(0).getFormats().get(0).getUrl());
                        }
                    }
                }
            }

            meta.setVideo(videoUrl);
            meta.setCatalogName(baoNiaoListItem.getCatalogName());
            meta.setTitle(baoNiaoListItem.getTitle());
            meta.setContent(baoNiaoListItem.getContent());
            meta.setCommentCount((int) baoNiaoListItem.getCommentCount());

            Intent intent = new Intent(itemView.getContext(), VideoPreActivity.class);
            if (videoUrl.size() > 0) {
                intent.putExtra("URL", videoUrl.get(0));
                itemView.getContext().startActivity(intent);
            }
        } else {
            try {
                JSONArray jsonArray = new JSONArray();
                for (int i = 0; baoNiaoListItem.getShortTitleStyle() != null && i < baoNiaoListItem.getShortTitleStyle().size(); i++) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("info", baoNiaoListItem.getContent());
                    if(baoNiaoListItem.getShortTitleStyle().get(i).getType().equals("image")){
                        jsonObject.put("src", baoNiaoListItem.getShortTitleStyle().get(i).getImgpath());
                    }else {
                        if (baoNiaoListItem.getTipoffinfoList() != null && baoNiaoListItem.getTipoffinfoList().size() > 0) {
                            if (baoNiaoListItem.getTipoffinfoList().get(0).getLiveAddress() != null && baoNiaoListItem.getTipoffinfoList().get(0).getLiveAddress().size() > 0) {
                                if (baoNiaoListItem.getTipoffinfoList().get(0).getLiveAddress().get(0).getFormats() != null && baoNiaoListItem.getTipoffinfoList().get(0).getLiveAddress().get(0).getFormats().size() > 0) {
                                    if(baoNiaoListItem.getShortTitleStyle()!=null && baoNiaoListItem.getShortTitleStyle().size()>0){
                                        if(!TextUtils.isEmpty(baoNiaoListItem.getShortTitleStyle().get(0).getImgpath())){
                                            jsonObject.put("src", baoNiaoListItem.getTipoffinfoList().get(0).getLiveAddress().get(0).getFormats().get(0).getImage());
                                        }
                                    }
                                }
                            }
                        }
                    }
                    jsonArray.put(jsonObject);
                }
                final ArticleItem imgArticle = new ArticleItem();
                imgArticle.setTitle(baoNiaoListItem.getCatalogName());
                imgArticle.setImage(jsonArray.toString());
                imgArticle.setType(TypeX.NEWS.PHOTOS);
                int imgIndex = index;
                if (baoNiaoListItem.getVideo() != null) {
                    imgIndex -= baoNiaoListItem.getVideo().size();
                }
                NewsItemClickUtils.OpenItemNewsHandle(itemView.getContext(), TypeX.NEWS.PHOTOS, imgArticle, new CatalogItem(), imgIndex, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public void setLastHeight(int lastHeight) {
        this.lastHeight = lastHeight;
    }
}